package cn.wolfcode.luowowo.website.param;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //支持解析参数的类型，满足参数上贴有@UserParam注解，并且参数类型是UserInfo，返回true，再继续执行resolveArgument的方法
        return methodParameter.hasParameterAnnotation(UserParam.class) && methodParameter.getParameterType() == UserInfo.class;
    }
     //以下方法的作用是执行结束后将返回的UserInfo对象注入到贴有@UserParam注解的方法参数上，达到自定义对象的注入
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Cookie cookie = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_INFO_COOKIE_NAME);
        System.out.println(cookie+"=======");
        UserInfo userInfo= null;
        if (cookie != null) {
            System.out.println(UserInfoKeyPrefix.USER_INFO_TOKEN);
            System.out.println(cookie.getValue());
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());

        }
        System.err.println(userInfo);
        return userInfo;
    }
}